#! /usr/local/bin/perl -w

###########################################################################
#
# ErrorGlob
#
###########################################################################
#
# An object which collects errors gradually, and then dumps them all at
# once.  An ErrorGlob has to be dumped before it's destroyed or it throws
# an exception.
#
# #########################################################################
#
# All the code herein is Copyright (c) 2004 ThinkGeek.
# Don't steal it.  Thanks.
#
###########################################################################

package ErrorGlob;

### Private ###############################################################

use strict;
use warnings;

use Geek::Dev::Debug;

use Carp;



###########################
# Subroutines:
###########################


sub new
{
	my ($class) = @_;

	my $this = { ERRORS => {} };
	bless $this, $class;
	return $this;
}


sub DESTROY
{
	my ($this) = @_;

	unless ($this->is_empty())
	{
		croak("ErrorGlob: never dumped");
	}
}


sub id
{
	my ($this, $id, $val) = @_;

	die("ErrorGlob: illegal value for ID (ERRORS)") if $id eq 'ERRORS';
	$this->{$id} = $val;
}


sub add
{
	my ($this, $err_id, $msg) = @_;

	$this->{ERRORS}->{$err_id} = $msg;
}


sub del
{
	my ($this, $err_id) = @_;

	return delete $this->{ERRORS}->{$err_id};
}


sub is_empty
{
	my ($this) = @_;

	print STDERR "ErrorGlob::is_empty : currently have ", scalar(keys %{$this->{ERRORS}}), " keys\n" if DEBUG >= 5;
	return keys %{ $this->{ERRORS} } == 0;
}


sub contains
{
	my ($this, $err_id) = @_;

	return exists $this->{ERRORS}->{$err_id};
}


sub dump
{
	my ($this) = @_;

	$this->is_empty() if DEBUG >= 5;			# will show # of error keys
	my $errs = delete $this->{ERRORS};			# get this out of the way

	my $glob = "";
	$glob .= "$_: $this->{$_}\n" foreach sort keys %$this;
	$glob .= "$_\n" foreach values %$errs;

	$this = { ERRORS => {} };					# so DESTROY knows it's been dumped
	return $glob;
}



###########################
# Return a true value:
###########################

1;
